package model

import (
	"fmt"
	"strings"
)

// UserQueryOptions 查询可选参数项
type QueryOptions struct {
	OrderFields  []*OrderField
	GroupBy      []string
	SelectFields []string
	Conditions   []string
	Pagination   bool
	OnlyCount    bool
	OnlyList     bool
}

type OrderDirection int

const (
	OrderByASC OrderDirection = iota + 1
	OrderByDESC
)

type OrderField struct {
	Key           string
	Direction     OrderDirection
	NullDirection string
}

// Create order fields key and define key index direction
func NewOrderFieldWithKeys(keys []string, directions ...map[int]OrderDirection) []*OrderField {
	m := make(map[int]OrderDirection)
	if len(directions) > 0 {
		m = directions[0]
	}

	fields := make([]*OrderField, len(keys))
	for i, key := range keys {
		d := OrderByASC
		if v, ok := m[i]; ok {
			d = v
		}

		fields[i] = NewOrderField(key, d, "")
	}

	return fields
}

func NewOrderFields(orderFields ...*OrderField) []*OrderField {
	return orderFields
}

func NewOrderField(key string, d OrderDirection, n ...string) *OrderField {

	var nullDirection string
	if len(n) > 0 {
		nullDirection = n[0]
	}
	return &OrderField{
		Key:           key,
		Direction:     d,
		NullDirection: nullDirection,
	}
}

func GetQueryOption(opts ...QueryOptions) QueryOptions {
	var opt QueryOptions
	if len(opts) > 0 {
		opt = opts[0]
	}
	return opt
}

// Define order fields convert function
type OrderFieldFunc func(string) string

func ParseOrder(items []*OrderField, handle ...OrderFieldFunc) string {
	orders := make([]string, len(items))

	for i, item := range items {
		key := item.Key
		if len(handle) > 0 {
			key = handle[0](key)
		}

		direction := "ASC"
		if item.Direction == OrderByDESC {
			direction = "DESC"
		}

		orders[i] = fmt.Sprintf("%s %s", key, direction+" "+item.NullDirection)
	}

	return strings.Join(orders, ",")
}
